import axios from 'axios'
import {hashHistory} from 'react-router'
import {timeout, baseUrl} from '@config'
import {message} from 'antd'
import {getQueryString} from "@utils/common";

const {CancelToken} = axios
// 默认axios配置
let baseConfig = {
    url:'',
    method: 'post',
    baseUrl:'',
    headers: {
        'Content-Type': 'text/plain',
        // 'X-Requested-With': 'XMLHttpRequest',
    },
    params: {},
    data: {},
    timeout: '',
    withCredentials: true, // default
    responseType: 'json', // default
    maxContentLength: 2000,
    validateStatus(status) {
        return status >= 200 && status < 300 // default
    },
}
// axios配置合并
baseConfig = {...baseConfig, timeout: timeout, baseUrl: baseUrl}

// 创建发起api的启动器
export const createApi = (api, options) => {
    const obj = getQueryString(window.location.href);
    let url = api;
    if (obj.key) {
        url = `${api}?key=${obj.key}`
        if (obj.sourceName) {
            url = `${url}&sourceName=${obj.sourceName}`
        }
    }
    return axiosByPost(`${url}`, options)
}
export const axiosByPost = (api, options) => {
    // api为方法
    if (typeof api === 'function') return api;
    /**
     *  可用参数：
     * (data:Object,sucess:Function,failure:Function,config:Object)
     */
    return (...reset) => {
        const data = reset[0] || {}
        const token = sessionStorage.getItem("token")
        if (token) data.token = token
        let success = null;
        let failure = null;
        let config = null;
        for (let i = 1; i < reset.length; i ++) {
            if (typeof reset[i] === 'function') {
                // 获取参数中的success、failure、config
                if (!success) {
                    success = reset[i]
                } else {
                    failure = reset[i]
                }
                if (Object.prototype.toString.call(reset[i]) === '[object Object]') config = reset[i]
            }
        }
        const hooks = {abort: null}
        const cancelToken = new CancelToken((a) => {
            hooks.abort = a
        })
        axios({
            ...baseConfig, ...options, ...config, url: api, data, cancelToken,
        })
            .then(res => res.data)
            .then(res => {
                switch (res.status) {
                    case 1: {
                        success && success(res)
                        break;
                    }
                    case 0: {
                        if(typeof failure === 'function'){
                            failure(res)
                        }else{
                            message.warning(res.msg)
                        }
                        break;
                    }
                    case -1: {
                        if(typeof failure === 'function'){
                            failure(res)
                        }
                        message.warning(res.msg)
                        hashHistory.replace('/login')
                        break;
                    }
                    default: {
                        if(typeof failure === 'function'){
                            failure(res)
                        }else{
                            message.warning('服务器返回参数无法识别')
                        }
                    }
                }
            })
            .catch(e => {
                if(axios.isCancel(e)){
                    if (process.env.NODE_ENV !== 'production') {
                        message.warning('Request canceled', e.message)
                    }
                }else{
                    if(typeof failure === 'function'){
                        failure({data:null,msg:e.code === 'ECONNABORTED'?'服务器连接超时':e.message,status})
                    }
                }
            })
        return hooks;
    }
}
